package com.woniu.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.car.common.BeanCopyUtils;

import com.woniu.car.common.ResponseEntity;

import com.woniu.car.exception.ParamException;
import com.woniu.car.exception.ServiceSException;
import com.woniu.car.Util.MyOssUtil;
import com.woniu.car.Util.NumberCreate;
import com.woniu.car.client.PlatformClient;
import com.woniu.car.domain.TGoods;
import com.woniu.car.domain.TProductCategory;
import com.woniu.car.domain.TSpec;
import com.woniu.car.domain.TSpecValue;
import com.woniu.car.dto.GetGoodsDto;
import com.woniu.car.dto.QueryGoodsAllSpec;


import com.woniu.car.mapper.TGoodsMapper;
import com.woniu.car.mapper.TProductCategoryMapper;
import com.woniu.car.mapper.TSpecMapper;
import com.woniu.car.mapper.TSpecValueMapper;
import com.woniu.car.ortherModel.ElasticGoodsAddParameter;
import com.woniu.car.ortherModel.ElasticGoodsUpdateParameter;
import com.woniu.car.param.AddGoodsParam;
import com.woniu.car.param.GroundingParam;
import com.woniu.car.param.ModifyGoodsParam;
import com.woniu.car.service.TGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;



import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


/**
 * <p>
 * 商品基础表 服务实现类
 * </p>
 *
 * @author chestnuts
 * @since 2021-06-21
 */
@Slf4j
@Service
public class TGoodsServiceImpl extends ServiceImpl<TGoodsMapper, TGoods> implements TGoodsService {

    @Autowired
    private TGoodsMapper goodsMapper;


    @Resource
    private TSpecMapper specMapper;

    @Resource
    private TSpecValueMapper specValueMapper;

    @Resource
    private TProductCategoryMapper productCategoryMapper;

    @Resource
    private PlatformClient platformClient;



//    ResponseEntity checkGoods(String goodsName){
//        log.info("查看该商品是否存在,{}",goodsName);
//        QueryWrapper<TGoods> query = new QueryWrapper<>();
//        QueryWrapper<TGoods> eq = query.eq("goods_name",goodsName);
//        //商品不存在 可添加商品
//        TGoods one;
//        try {
//             one = goodsMapper.selectOne(eq);
//        } catch (Exception e) {
//
//           throw new RuntimeException("该商品已存在,请勿重复添加");
//
//        }
//        return new ResponseEntity().setObject(one);
//    }

//    @Override
//    public ResponseEntity addGoods(AddGoodsParam addGoodsParam,MultipartFile file,Integer id) throws GoodsNullException, IOException {


        @Override
    public ResponseEntity addGoods(AddGoodsParam addGoodsParam,MultipartFile file,Integer id) throws ServiceSException, IOException, ParamException {

        log.info("查看该商品是否存在,{}",addGoodsParam.getGoodsName());
        QueryWrapper<TGoods> query = new QueryWrapper<>();
        query.eq("goods_name",addGoodsParam.getGoodsName());
        //商品不存在 可添加商品
        TGoods one= goodsMapper.selectOne(query);
        if(null != one){
            throw new ServiceSException("该商品已存在,请勿重复添加");
        }
        TProductCategory tProductCategory = productCategoryMapper.selectById(addGoodsParam.getCategoryId());

        if(tProductCategory.getCategoryLevel()<=1){
            throw new ParamException("该分类不是基础分类,请重新选择分类");
        }

        TGoods tGoods = new TGoods();
        if(tProductCategory==null){
            throw new ParamException("该分类不存在,请先添加分类");
        }
        BeanUtils.copyProperties(addGoodsParam,tGoods);

        String upload = MyOssUtil.upload(file);

        //生成商品编号
        String goodsNO = NumberCreate.getGoodsNO();
        //生成商品编号
        tGoods.setGoodsNo(goodsNO);
        //生成创建时间
        tGoods.setCreateTime(Long.toString(System.currentTimeMillis()));
        //写入创建人编号
        tGoods.setCreateNo(id.toString());
        //最后入库时间
        tGoods.setLastAddTime(Long.toString(System.currentTimeMillis()));
        //设定默认状态
        tGoods.setImage(upload);
        tGoods.setWeight(0.00);
        tGoods.setStockCount(0);
        tGoods.setStatus(0);
        //最后入库数量为0
        tGoods.setLastAddCount(0);
        int insert = goodsMapper.insert(tGoods);
        QueryWrapper<TGoods> query1 = new QueryWrapper<>();
        QueryWrapper<TGoods> eq1 = query.eq("goods_name", addGoodsParam.getGoodsName());
        one = goodsMapper.selectOne(eq1);
        return new ResponseEntity().setCode(200).setMsg("新增成功").setObject(one);
    }



    @Override
    public ResponseEntity putGoods(ModifyGoodsParam modifyGoodsParam) throws ServiceSException{
        log.info("修改商品信息,{}",modifyGoodsParam);

        TGoods tGoods = goodsMapper.selectById(modifyGoodsParam.getGoodsId());

        if(null == tGoods){
            throw new ServiceSException("该商品不存在");
        }

        TGoods tGoods1 = new TGoods();

        tGoods1=tGoods;

        ElasticGoodsUpdateParameter updateParameter = new ElasticGoodsUpdateParameter();

        BeanCopyUtils.copyProperties(modifyGoodsParam,tGoods);

        ResponseEntity goods = this.getGoods(tGoods.getGoodsId());

        GetGoodsDto getGoodsDto=(GetGoodsDto)goods.getObject();

        List<QueryGoodsAllSpec> speces = getGoodsDto.getSpeces();

        BeanCopyUtils.copyProperties(getGoodsDto,updateParameter);

        Integer specValueId = modifyGoodsParam.getSpecValueId();

        TSpecValue tSpecValue = specValueMapper.selectById(specValueId);

        TSpec tSpec = specMapper.selectById(tSpecValue.getSpecId());

        updateParameter.setSpecName(tSpec.getSpecName());

        updateParameter.setSpecValue(tSpecValue.getSpecValue());

        ResponseEntity responseEntity1 = this.platformClient.ElasticGoodsSearch(tGoods.getGoodsNo());

        ResponseEntity responseEntity = this.platformClient.ElasticGoodsUpdate(updateParameter);

        log.info("--------,{}",responseEntity.getObject());

        if(responseEntity1.getObject()==null){
            goodsMapper.updateById(tGoods);
            return new ResponseEntity().setCode(200).setMsg("基础数据已修改.(改商品并未上架)").setObject(tGoods);
        }

        int i = goodsMapper.updateById(tGoods);

        return i>0?new ResponseEntity().setCode(200).setMsg("基础数据已修改.(上架商品信息已修改)").setObject(tGoods):new ResponseEntity().setCode(200).setMsg("修改失败").setObject(tGoods1);
    }

    @Override
    public ResponseEntity delGoods(Integer goodsId){

        TGoods tGoods = goodsMapper.selectById(goodsId);
        if(tGoods==null) new ResponseEntity().setCode(200).setMsg("该商品不存在").setObject(tGoods);
        int i1 = goodsMapper.deleteById(goodsId);


        return i1>0?new ResponseEntity().setCode(200).setMsg("删除成功").setObject(tGoods):new ResponseEntity().setCode(200).setMsg("修改失败").setObject(tGoods);
    }

    @Override
    public ResponseEntity getGoods(Integer goodsId) {
        //商品详情 :商品名 商品编号 商品分类名 商品介绍 商品价格 商品图片 规格详情 
        TGoods tGoods = goodsMapper.selectById(goodsId);
        if(tGoods==null)return new ResponseEntity().setCode(500).setMsg("该商品不存在").setObject(goodsId);
        Integer categoryId = tGoods.getCategoryId();
        TProductCategory tProductCategory = productCategoryMapper.selectById(categoryId);
        List<QueryGoodsAllSpec> speces = specMapper.getSpeces(categoryId);
        GetGoodsDto getGoodsDto = new GetGoodsDto();
        BeanUtils.copyProperties(tGoods,getGoodsDto);
        getGoodsDto.setCategoryName(tProductCategory.getCategoryName());
        getGoodsDto.setSpeces(speces);
        return new ResponseEntity().setCode(200).setMsg("操作成功").setObject(getGoodsDto);
    }


    @Override
    public ResponseEntity groundGoods(GroundingParam groundingParam) throws ParamException {

        //商品下单
        //通过商品的id查找商品的基础信息
        //需要商品的具体规格


        Integer goodsId = groundingParam.getGoodsId();

        ResponseEntity goods = this.getGoods(goodsId);

        GetGoodsDto getGoodsDto=(GetGoodsDto)goods.getObject();
        List<QueryGoodsAllSpec> speces = getGoodsDto.getSpeces();


        Integer specValueId = groundingParam.getSpecValueId();

        TSpecValue tSpecValue = specValueMapper.selectById(specValueId);
//        int o=0;
//        for(QueryGoodsAllSpec i: speces){
//            if(i.getSpecId()==groundingParam.getSpecValueId()){
//                o=-1;
//            }
//        }
//        if(o!=-1){
//            throw new ParamException("该商品不存在该规格组,请先添加相应规格组");
//        }
        if(tSpecValue==null){
            throw new ParamException("该商品不存在该规格组,请先添加相应规格组");
        }

        TSpec tSpec = specMapper.selectById(tSpecValue.getSpecId());


        ElasticGoodsAddParameter elasticGoodsAddParameter = new ElasticGoodsAddParameter();
        BeanUtils.copyProperties(getGoodsDto,elasticGoodsAddParameter);

        elasticGoodsAddParameter.setSpecName(tSpec.getSpecName());
        elasticGoodsAddParameter.setSpecValue(tSpecValue.getSpecValue());

        ResponseEntity responseEntity = platformClient.ElasticGoodsAdd(elasticGoodsAddParameter);


        return responseEntity;
    }

    @Override
    public ResponseEntity queryGoods(Integer gategoryId,Integer pageIdx) {
        QueryWrapper<TGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", gategoryId);
        List<TGoods> tGoods = goodsMapper.selectList(wrapper);
        return new ResponseEntity().setObject(tGoods).setMsg("查询成功").setCode(200);
    }

    @Override
    public ResponseEntity pullGoods(Integer goodsId) {
        TGoods tGoods = goodsMapper.selectById(goodsId);
        ResponseEntity responseEntity = platformClient.ElasticGoodsDelete(tGoods.getGoodsNo());
        tGoods.setStatus(0);
        goodsMapper.updateById(tGoods);
        return responseEntity;
    }

    @Override
    public ResponseEntity searchPutingGoods(String keyword) {
        ResponseEntity responseEntity = platformClient.ElasticGoodsSearch(keyword);
        return responseEntity;
    }

    @Override
    public ResponseEntity queryAllGoods(Integer pageIndex,Long pageSize) {

        Page<TGoods> pageParam = new Page(pageIndex,pageSize==0?5:pageSize);
        IPage<TGoods> pageResult = goodsMapper.selectPage(pageParam,null);
        return new ResponseEntity().setCode(200).setObject(pageResult).setMsg("查询成功");
    }


    @Override
    public String uploadGoodsImg(MultipartFile file) {
        log.info("上传商品图片,{}",file);
        String upload = null;
        try {
            upload = MyOssUtil.upload(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return upload;
    }


}
